package jaux.tank.generator.jd.components;

import java.awt.Component;
import java.util.Collection;
import java.util.Collections;
import java.util.function.Supplier;

import javax.swing.DefaultCellEditor;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class JdUniqueTextCellEditor  extends DefaultCellEditor {
	private static final long serialVersionUID = 1L;
	Object originalValue;
	Collection<String> values;
	Supplier<Collection<String>> valuesSupplier;
	String errorMessage ;
	public JdUniqueTextCellEditor(Supplier<Collection<String>> valuesSupplier, String errorMessage) {
		super(new JTextField());
		this.errorMessage = errorMessage;
		this.valuesSupplier = valuesSupplier;
	}
	@Override
	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
			int column) {
		originalValue = value;
		values = valuesSupplier!=null?valuesSupplier.get():Collections.emptyList();
		return super.getTableCellEditorComponent(table, value, isSelected, row, column);
	}
	@Override
	protected void fireEditingStopped() {
		Object newName = this.getCellEditorValue();
		if( newName != null 
				&& !newName.equals(originalValue)
				&& values !=null 
				&& values.contains(newName) ) {
				JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this.getComponent()), errorMessage);
				super.cancelCellEditing();
				return;
			
		}
		super.fireEditingStopped();
	}
}
